import logging
from django.shortcuts import HttpResponse
from rest_framework.views import APIView
from luffy.utils.geetest import GeetestLib
from rest_framework.response import Response
from rest_framework import status
from .utils import get_user
from luffy.settings.dev import PC_GEETEST_ID, PC_GEETEST_KEY

logger = logging.getLogger('django')


class CaptchaAPIView(APIView):
    """
    滑动验证码接口
    """
    user_id = 'test'  # 用户名
    status = 1

    def get(self, request):
        """
        生成极验验证所需数据
        :param request:
        :return:
        """
        username = request.query_params.get('username')
        user = get_user(username)
        if user is None:
            return Response({'msg': '用户名不存在！'}, status=status.HTTP_400_BAD_REQUEST)
        self.user_id = user.id
        gt = GeetestLib(PC_GEETEST_ID, PC_GEETEST_KEY)
        self.status = gt.pre_process(self.user_id)
        # todo user_id 和 status保存到另外一个地方，比如'redis'中，以防止并发时出现多线程共享全局变量出错！
        # status ：1成功，0失败
        response_str = gt.get_response_str()
        return HttpResponse(response_str)
        """
                {
                "success": 1, 
                "gt": "5e876edb2bda195c265416b70e7389a7", 
                "challenge": "20f862ef3da4b8333ced3d6806ec090b", 
                "new_captcha":true
                }
                """

    def post(self, request):
        """
        校验极验验证提交过来的数据
        :param request:
        :return:
        """
        gt = GeetestLib(PC_GEETEST_ID, PC_GEETEST_KEY)
        challenge = request.data.get(gt.FN_CHALLENGE, '')
        validate = request.data.get(gt.FN_VALIDATE, '')
        seccode = request.data.get(gt.FN_SECCODE, '')

        if self.status:
            result = gt.success_validate(challenge, validate, seccode, self.user_id)
        else:
            result = gt.failback_validate(challenge, validate, seccode)
        result = {"status": "success"} if result else {"status": "fail"}
        return Response(result)


from rest_framework.generics import CreateAPIView
from rest_framework.views import APIView
from . import models
from .serializers import UserModelSerializer


class RegisterAPIView(CreateAPIView):
    """
    注册新用户
    """
    queryset = models.User.objects.all()
    serializer_class = UserModelSerializer


class MobileAPIView(APIView):
    """
    查询手机号是否已存在于数据库
    """

    def get(self, request, mobile):
        user = get_user(mobile)
        if user is not None:
            return Response({'msg': '手机号已注册！'}, status=status.HTTP_400_BAD_REQUEST)

        return Response({'msg': 'OK'})


import random
from django_redis import get_redis_connection
from luffy.settings.contants import (SMS_EXPIRE_TIME, SMS_INTERVAL_TIME)
from luffy.libs.yuntongxun.sms import CCP


class SMSAPIView(APIView):
    """
    云通讯发送短信接口
    """

    def get(self, request, mobile):
        # 查询该手机号是否在 60 秒内已经发送过短信
        redis_conn = get_redis_connection('sms_code')

        check_ret = redis_conn.get('mobile_%s' % mobile)
        # 找不到默认返回的是None
        if check_ret is not None:
            return Response({'msg': '60秒内只能发送一次短信验证码，请勿频繁操作！'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            # 1、生成验证码，如果随机数生成为 1，则在前面补 5个 0
            sms_code = "%06d" % random.randint(0, 999999)
            pipe = redis_conn.pipeline()
            pipe.multi()  # 开启批量操作

            # 2、redis中保存验证码(有效期 5 分钟）
            pipe.setex('sms_%s' % mobile, SMS_EXPIRE_TIME, sms_code)  # --setex k 60 v
            # redis_conn.setex('sms_%s' % mobile, contants.SMS_EXPIRE_TIME, sms_code) #--setex k 60 v

            # 3、限制短信发送时间间隔（60 秒之内只能发送一次）
            pipe.setex('mobile_%s' % mobile, SMS_INTERVAL_TIME, '_')

            # redis_conn.setex('mobile_%s' % mobile, contants.SMS_INTERVAL_TIME, '_')

            # 执行管道中的两条命令
            pipe.execute()

            # 4、调用云通讯提供的 SDK 来发送短信

            # (1)、利用 celery 进行异步发送短信(未知错误！)
            from mycelery.sms.tasks import send_sms
            send_sms.delay(mobile, sms_code)
            return Response({'msg': '发送短信成功！'})

            # (2)、直接调用云通讯提供的 SDK
            # ccp = CCP()
            # #  to,                datas,             temp_id
            # # '17361537209',      ['1234',"5"],      1(使用短信模板1)               注："5"是分钟数
            # ret = ccp.send_template_sms(mobile, [sms_code, SMS_EXPIRE_TIME // 60], 1)
            # if not ret:
            #     logger.error("%s 发送短信失败" % mobile)
            #     return Response({'msg': '短信发送失败'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
            # return Response({'msg': '发送短信成功！'})

        except:
            return Response({'msg': '未知错误'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


